#!/usr/bin/env perl
# Simple check of the CPU per node in the cluster using pywrekamapd.py

# Basile Clout,
# November 2007

use Getopt::Long;
use strict;

sub usage(){

  print <<EOF;

Usage: $0 [-f file containing the list of nodes] [-h print help and
exit] [-u user] [-l logfile] [--size size of pim2 test
(DEFAULT=1000)] [--min unit=1 goes for the minimum CPU] [--max unit 1
goes for the maximum (DEFAULT)] <list of nodes>

EOF
  exit;
}


my $file;
my $help;
my $user="root";
my @hosts;
my $ssh = "ssh";
my $logfile = "chkCPU.log";
my $mode=0;			# 0 is max, 1 is min
my $max_fl;
my $min_fl;
my $size = 5000;

GetOptions("f=s"=>\$file, "h"=>\$help, "u=s"=>\$user, "l=s"=>\$logfile, "size=i"=>\$size, "max"=>\$max_fl, "min"=>\$min_fl);

$mode = 0 if ($max_fl);
$mode = 1 if ($min_fl);

my $wmapd_bin = "../daemons/hemapd.py";
my $wmapd_fl = "--net_off --cpu_on --set_pim2size $size --set_user $user";

my %hash;

usage() if ($help);

if ($#ARGV < 0 and !$file){
  print "Please enter at least one node, either on the command line or in a file\n";
  usage();
}

if ($#ARGV > -1){
  @hosts = sort @ARGV;
}else{
  open(HOSTS, "<$file") or die("$0: Impossible to open file $file: $!");
  my @oldhosts = <HOSTS>;
  @hosts = sort split /\s/, $oldhosts[$#oldhosts];
  close(HOSTS);
}
#print join(' & ', @hosts), "\n";

open LOG, ">$logfile" or die "Impossible to create logfile $logfile: $!";
my ($sec, $min, $hrs, $day, $month, $year) = (localtime) [0,1,2,3,4,5];
my $date = sprintf("%04d-%02d-%02d %d:%d:%d\n", $year+1900, $month+1, $day, $hrs, $min, $sec);
print LOG "#Basile Clout, $date \n\n";

# Real loop
foreach my $node (@hosts){
  
  chomp $node;
  my $order = "$ssh ${node} \"$wmapd_bin $wmapd_fl\"";
  
  open ORDER, "$order |";
  my @content = <ORDER>;
  print LOG "order on $node output: ",  join('',@content), "\n";

  foreach my $line (@content){
    if ($line =~ /^cpu\s(\d+\.\d+)\s$user$/){
      $hash{$node}=$1;
    }
  }
}

my $e;
if ($mode==0){
  $e=0;
  foreach my $val (values %hash){
    if ($val>$e){
      $e=$val
    }
  }
}else{
  $e=10000000;
  foreach my $val (values %hash){
    if ($val<$e){
      $e=$val;
    }
  }
}
print LOG "mode = $mode, e = $e\n";

my $ratio;
if ($mode==0){
  foreach my $mykey (sort keys %hash){
    $ratio = $e/$hash{$mykey};
    printf "%s %.2f %.2f\n", $mykey, $hash{$mykey}, $ratio;
    printf LOG "%s %.2f %.2f\n", $mykey, $hash{$mykey}, $ratio;
  }
}else{
  foreach my $k (sort keys %hash){
    $ratio = $hash{$k}/$e;
    printf "%s %.2f %.2f\n", $k, $hash{$k}, $ratio;
    printf LOG "%s %.2f %.2f\n", $k, $hash{$k}, $ratio;
  }
}

  
  


